package com.example.administrator.tiyuapp.NewsFragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.administrator.tiyuapp.App;
import com.example.administrator.tiyuapp.Constants;
import com.example.administrator.tiyuapp.NewsFragment.adapter.MyViewPagerAdapter;
import com.example.administrator.tiyuapp.NewsFragment.beans.Channels;
import com.example.administrator.tiyuapp.NewsFragment.fragments.MyFragment;
import com.example.administrator.tiyuapp.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;



/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFragment extends Fragment {


    private ViewPager viewPager;//控件
    private TabLayout tabLayout;//layout
    private List<Channels>titles;//tablayout的内容
    private List<Fragment>fragments;//VIewpager的内容
    private MyViewPagerAdapter adapter;
    private RequestQueue requestQueue;//请求队列
    private JsonObjectRequest jsonObjectRequest;//请求

    public NewsFragment() {
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        titles=new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            titles.add(new Channels("item"+i));
//        }
        fragments=new ArrayList<>();

        //网络请求
        netRequest();

    }

    //网络请求
    private void netRequest() {
        requestQueue = App.getApp().getRequestQueue();
        jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Constants.TitlesUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i("haha","网络请求成功"+response);
                try {
                    JSONObject data = response.getJSONObject("data");
                    JSONArray channels = data.getJSONArray("channels");
                    for (int i = 0; i < channels.length(); i++) {
                        JSONObject jsonObject = channels.getJSONObject(i);
                        Channels bean = new Channels();
                        bean.parseJSon(jsonObject);
                        fragments.add(new MyFragment());
                        titles.add(bean);
                    }
//                    Log.i("haha","title的数量："+titles.size());
//                    if(viewPager!=null){

//                    adapter.notify();
//                    }
                    adapter=new MyViewPagerAdapter(getChildFragmentManager(),fragments,titles);
                    viewPager.setAdapter(adapter);
                    tabLayout.setupWithViewPager(viewPager);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.i("haha", "fragment中的title解析异常");
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("haha", "网络请求失败");
            }
        });
        jsonObjectRequest.setTag("json");//为请求添加标签
        requestQueue.add(jsonObjectRequest);//将请求加入请求队列中，相当于开启网络请求
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new, container, false);
        //初始化控件
        initView(view);
        return view;
    }
    //初始化控件
    private void initView(View view) {

        viewPager = (ViewPager) view.findViewById(R.id.fragment_news_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.fragment_news_tablayout);
        //将控件TabLayout与Viewpager关联起来



    }

    /**
     * 在onDestroy（）方法中，取消网络请求
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        requestQueue.cancelAll("json");//取消请求
    }
}
